import uvicorn
from fastapi import FastAPI, responses, status
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

origins = [
    "*",
]

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


class UserModel(BaseModel):
    username: str
    password: str

@app.post("/login")
async def login(user: UserModel):
    with open(file="./user.db", mode="r", encoding="utf8") as user_file:
        line = user_file.readline()
        while line:
            username, password = line.strip().split(",")
            if username == user.username and password==user.password:
                return {"message": "success"}
            line = user_file.readline()
        return responses.JSONResponse(content={"code":status.HTTP_400_BAD_REQUEST, "message": "fail"}, status_code=status.HTTP_400_BAD_REQUEST)


@app.post("/register")
async def register(user: UserModel):
    if user.username and user.password:
        with open(file="./user.db", mode="a", encoding="utf8") as user_file:
            user_file.write(f"{user.username},{user.password}\n")
        return {"message": "success"}
    return responses.JSONResponse(content={"message": "fail"}, status_code=status.HTTP_400_BAD_REQUEST)


@app.get("/dashboard")
async def dashboard():
    week = []
    value = []
    with open(file="./data.db", mode="r", encoding="utf8") as data_file:
        for line in data_file.readlines():
            w, v = line.strip().split(",")
            week.append(w)
            value.append(int(v))
    return [week, value]

if __name__ == "__main__":
    uvicorn.run(
        app='main:app',
        host="0.0.0.0",
        port=4444,
        reload=True,
        debug=True
    )
